package com.zheng.shop.rpc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.shop.common.Enum.ProductStatusType;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.mapper.ShopProductMapper;
import com.zheng.shop.dao.model.ShopProduct;
import com.zheng.shop.dao.model.ShopProductAttribute;
import com.zheng.shop.dao.model.ShopProductImage;
import com.zheng.shop.dao.model.ShopProductParam;
import com.zheng.shop.rpc.api.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author likun
 * @since 2017-12-29
 */
@Service
@Transactional(rollbackFor = ShopException.class)
@BaseService
public class ShopProductServiceImpl extends BaseServiceImpl<ShopProductMapper, ShopProduct> implements ShopProductService {
    private static Logger _log = LoggerFactory.getLogger(ShopProductServiceImpl.class);

    @Autowired
    private ShopProductMapper productMapper;
    @Autowired
    private ShopSkuService skuService;
    @Autowired
    private ShopProductParamService productParamService;
    @Autowired
    private ShopProductImageService productImageService;
    @Autowired
    private ShopProductAttributeService productAttributeService;
    @Autowired
    private ShopSkuAttributeService skuAttributeService;

    @Override
    public List<Map<String, Object>> selectProductMapList(String search, String sort, String order, int offset, int limit, Integer categoryId) {
        if (StringUtils.isNotBlank(search)) {
            search = "%" + search + "%";
        } else {
            search = null;
        }
        String category = null;
        if (null != categoryId) {
            category = "%\\_" + categoryId + "\\_%";
        }
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            sort = sort + " " + order;
        } else {
            sort = null;
        }
        return productMapper.selectProductMap(search, sort, offset, limit, category);
    }

    @Override
    public int selectProductCount(String search, String sort, String order, int offset, int limit, Integer categoryId) {
        String category = null;
        if (null != categoryId) {
            category = "%\\_" + categoryId + "\\_%";
        }
        if (StringUtils.isNotBlank(search)) {
            search = "%" + search + "%";
        } else {
            search = null;
        }
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            sort = sort + " " + order;
        } else {
            sort = null;
        }
        return productMapper.selectProductCount(search, sort, offset, limit, category);
    }

    @Override
    public boolean createProduct(JSONObject param) throws ShopException {
        JSONObject productJson = param.getJSONObject("product");
        ShopProduct product = productJson.toJavaObject(ShopProduct.class);
        //被选中的属性id
        JSONArray skuArray = param.getJSONArray("skus");
        JSONArray checkAttributeIdArray = new JSONArray();
        if (skuArray.size() > 0) {
            JSONArray attributes = skuArray.getJSONObject(0).getJSONArray("attribute");
            if (null != attributes) {
                for (int i = 0; i < attributes.size(); i++) {
                    JSONObject attribute = attributes.getJSONObject(i);
                    checkAttributeIdArray.add(attribute.getString("attributeKeyId"));
                }
            }
        }
        product.setCtime(new Date());
        product.setStatus(ProductStatusType.NORMAL.key);
        product.setCheckAttributeIds(checkAttributeIdArray.toJSONString());
        if (insert(product)) {
            JSONArray params = productJson.getJSONArray("param");
            JSONArray images = productJson.getJSONArray("images");
            JSONArray attributes = param.getJSONArray("attributes");
            //添加参数
            List<ShopProductParam> paramList = params.toJavaList(ShopProductParam.class);
            for (ShopProductParam productParam : paramList) {
                productParam.setProductId(product.getId());
                if (!productParamService.insert(productParam)) {
                    throw new ShopException("添加商品参数失败");
                }
            }
            //添加图片 改为单个图片 isMain无效化 第一个图 为主图
            ShopProductImage image = new ShopProductImage();
            image.setImagePath(images.toJSONString());
            image.setProductId(product.getId());
            if (!productImageService.insert(image)) {
                throw new ShopException("添加商品图片失败");
            }

            //添加属性
            for (int i = 0; i < attributes.size(); i++) {
                JSONObject obj = attributes.getJSONObject(i);
                ShopProductAttribute productAttribute = obj.toJavaObject(ShopProductAttribute.class);
                JSONArray values = obj.getJSONArray("values");
                for (int j = 0; j < values.size(); j++) {
                    JSONObject value = values.getJSONObject(j);
                    productAttribute.setProductId(product.getId());
                    productAttribute.setAttributeValue(value.getString("value"));
                    if (!productAttributeService.insert(productAttribute)) {
                        throw new ShopException("添加商品属性失败");
                    }
                }
            }
            //添加sku
            int skuNum = skuService.createSkuList(param, product);
        }
        return true;
    }

    @Override
    public boolean updateProduct(JSONObject param) throws ShopException {
        JSONObject productJson = param.getJSONObject("product");
        ShopProduct product = productJson.toJavaObject(ShopProduct.class);
        Boolean marketable = selectById(product.getId()).getMarketable();
        if (marketable) {
            throw new ShopException("请先下架当前商品！");
        }
        //被选中的属性id
        JSONArray skuArray = param.getJSONArray("skus");
        JSONArray checkAttributeIdArray = new JSONArray();
        if (skuArray.size() > 0) {
            JSONArray attributes = skuArray.getJSONObject(0).getJSONArray("attribute");
            if (null != attributes) {
                for (int i = 0; i < attributes.size(); i++) {
                    JSONObject attribute = attributes.getJSONObject(i);
                    checkAttributeIdArray.add(attribute.getString("attributeKeyId"));
                }
            }
        }
        product.setMtime(new Date());
        product.setCheckAttributeIds(checkAttributeIdArray.toJSONString());
        if (updateById(product)) {
            JSONArray params = productJson.getJSONArray("param");
            JSONArray images = productJson.getJSONArray("images");
            JSONArray attributes = param.getJSONArray("attributes");
            //添加参数
            List<ShopProductParam> paramList = params.toJavaList(ShopProductParam.class);
            //先删除之前的所有参数
            EntityWrapper<ShopProductParam> productParamEntityWrapper = new EntityWrapper<>();
            productParamEntityWrapper.where("product_id=" + product.getId());
            productParamService.delete(productParamEntityWrapper);
            for (ShopProductParam productParam : paramList) {
                productParam.setProductId(product.getId());
                if (!productParamService.insert(productParam)) {
                    throw new ShopException("添加商品参数失败");
                }
            }
            //添加图片 改为单个图片 isMain无效化 第一个图 为主图
            EntityWrapper<ShopProductImage> productImageEntityWrapper = new EntityWrapper<>();
            productImageEntityWrapper.where("product_id=" + product.getId());
            ShopProductImage image = productImageService.selectOne(productImageEntityWrapper);
            image.setImagePath(images.toJSONString());
            if (!productImageService.updateById(image)) {
                throw new ShopException("更新商品图片失败");
            }
            //删除所有属性
            EntityWrapper<ShopProductAttribute> productAttributeEntityWrapper = new EntityWrapper<>();
            productAttributeEntityWrapper.where("product_id=" + product.getId());
            productAttributeService.delete(productAttributeEntityWrapper);
            //添加属性
            for (int i = 0; i < attributes.size(); i++) {
                JSONObject obj = attributes.getJSONObject(i);
                ShopProductAttribute productAttribute = obj.toJavaObject(ShopProductAttribute.class);
                JSONArray values = obj.getJSONArray("values");
                for (int j = 0; j < values.size(); j++) {
                    JSONObject value = values.getJSONObject(j);
                    productAttribute.setProductId(product.getId());
                    productAttribute.setAttributeValue(value.getString("value"));
                    if (!productAttributeService.insert(productAttribute)) {
                        throw new ShopException("添加商品属性失败");
                    }
                }
            }
            //添加sku
            int skuNum = skuService.updateSkuList(param, product);
        }
        if (updateById(product)) {
            return true;
        } else {
            throw new ShopException("修改商品失败！");
        }
    }

    @Override
    public boolean deleteProduct() {
        //删除商品 注意点 1 不删除任何与SKU相关的内容 2
        return false;
    }

    public Map<String, Object> selectProduct(Integer productId) {
        return productMapper.selectProduct(productId);
    }
}
